<?php

/**
 * Description of Deal Controller
 *
 * @author Vu
 */
class Admin_Cms_DealController extends My_Controller_Action {

	public function init(){
		parent::init();
		
		$auth = Zend_Auth::getInstance();
        
        if(!$auth->hasIdentity())
        { 
            $this->_redirect("user/account/login");
        }
        
        if ($this->isAccess($auth->getIdentity()->group_id, 4))
        {
			//to do
		} else {
            die("Access denied");
        }
	}   

    protected function _findexts($filename) {
        $filename = strtolower($filename);
        $exts = preg_split("/[\.]+/", $filename);
        $n = count($exts) - 1;
        $exts = $exts[$n];
        return $exts;
    }

    public function getForm($image = null) {
        $this->view->addHelperPath(APPLICATION_PATH . '/library/ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');
        $categoryModel = $this->loadModel('admin_cms', 'Category');
        $categories = $categoryModel->getAll();

        //die(Zend_Debug::dump($categories));

        $form = new Zend_Form();

        $form->setAttrib('enctype', 'multipart/form-data');

        $form->addElement('text', 'deal_title', array(
            'label' => 'Tiêu đề',
            'size' => 70,
            'required' => true));

        $categoryElement = new Zend_Form_Element_Select('category_id');
        $categoryElement->setLabel('Danh mục');

        foreach ($categories as $category) {
            $categoryElement->addMultiOption($category->category_id, $category->name);
        }

        $form->addElement($categoryElement);

        $startedElement = new ZendX_JQuery_Form_Element_DatePicker('started',
                        array('jQueryParams' => array('dateFormat' => 'yy-mm-dd'), 'size' => 70)
        );
        $startedElement->setLabel('Ngày bắt đầu')->setRequired();
        $form->addElement($startedElement);

        $deadlineElement = new ZendX_JQuery_Form_Element_DatePicker('deadline',
                        array('jQueryParams' => array('dateFormat' => 'yy-mm-dd'), 'size' => 70)
        );
        $deadlineElement->setLabel('Ngày kết thúc')->setRequired();
        $form->addElement($deadlineElement);
        
        //price
        $form->addElement('text', 'product_price', array(
                    'label' => 'Giá phiếu giảm giá *',
                    'size' => 70,
                    'validators' => array(array('regex', false, '/^[0-9]/i')),
                    'required' => true))
                ->addElement('text', 'value', array(
                    'label' => 'Giá gốc *',
                    'size' => 70,
                    'validators' => array(array('regex', false, '/^[0-9]/i')),
                    'required' => true))
                //supplier
                ->addElement('text', 'supplier_name', array(
                    'label' => 'Tên nhà cung cấp *',
                    'size' => 70,
                    'required' => true))
                ->addElement('text', 'supplier_url', array(
                    'label' => 'Website *',
                    'size' => 70,
                    'validators' => array(array('regex', false, '|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i')),
                    'required' => true))
                ->addElement('text', 'supplier_contact', array(
                    'label' => 'Thông tin liên hệ *',
                    'size' => 70,
                    'required' => true))
                //quantity
                ->addElement('text', 'deal_quantity', array(
                    'label' => 'Số lượng phiếu giảm giá *',
                    'size' => 70,
                    'validators' => array(array('regex', false, '/^[0-9]/i')),
                    'required' => true));
                
        //update 5 fields
        $form->addElement('text', 'number_A', array(
            'label' => 'Số A *',
            'size' => 70,
        	'validators' => array(array('regex', false, '/^[0-9]/i')),
            'required' => true));
        $form->addElement('text', 'number_B', array(
            'label' => 'Số B *',
            'size' => 70,
        	'validators' => array(array('regex', false, '/^[0-9]/i')),
            'required' => true));
        
        //file

        $avatarUploader = new Zend_Form_Element_File('deal_avatar');
        $avatarUploader->setLabel('Upload hình đại diện')
                ->setDestination(UPLOAD_DESTINATION . '/images/deals/');
        $avatarUploader->addValidator('Count', false, 1);
        $avatarUploader->addValidator('Size', false, 1048576);
        $avatarUploader->addValidator('Extension', false, 'jpg,png,gif');

        $form->addElement($avatarUploader, 'deal_avatar');

        if ($image) {
            $imageElement = new Zend_Form_Element_Image(array(
                        'name' => 'deal_avatar_thumbnail',
                        'label' => 'Deal Avatar',
                        'width' => 380,
                        'src' => $this->view->baseUrl('public/upload/images/deals/' . $image)));
            $form->addElement($imageElement);
        }


        $form->addElement('textarea', 'deal_notes', array(
                    'label' => 'Thông tin lưu ý *',
                    'required' => true))
                //intro
                ->addElement('textarea', 'deal_intro', array(
                    'label' => 'Giới thiệu ngắn *',
                    'required' => true))
                //fulltext
                ->addElement('textarea', 'deal_fulltext', array(
                    'label' => 'Nội dung *',
                    'required' => true));

        //status
        $statusRadio = $form->createElement('radio', 'status');
        $statusRadio->setLabel('Trạng thái *')
                ->addMultiOptions(array(
                    0 => 'unpublished',
                    1 => 'published'))
                ->setSeparator('<br />')
                ->setRequired(true);
        $form->addElement($statusRadio);
        $form->addElement('hidden', 'deal_id');
        $form->addElement('submit', 'Save', array(
            'label' => 'Save', 'class' => 'button'));

        return $form;
    }

    public function indexAction() {
        $this->view->rightAdminModules('right');
        
        $this->view->by = $this->_request->getParam("by", "d.created");
        $this->view->order = $this->_request->getParam("order", "desc");
        $this->view->filter = $this->_request->getParam("filter", "");
        
        Zend_View_Helper_PaginationControl::setDefaultViewPartial('pagination.phtml');
        $model = $this->loadModel('admin_cms', 'Deal');
        $this->view->paginator = $model->getAllDeals($this->getRequest()->getParam('page', 1), $this->view->by.' '.$this->view->order, $this->view->filter);
    }

    public function addAction() {
        $this->view->rightAdminModules('right');

        $form = $this->getForm();
        $form->setAction($this->view->baseUrl('index.php/admin_cms/deal/add'))->setMethod('post');

        if (!$this->_request->isPost()) {
            $this->view->form = $form;
            return $this->render('add');

            $this->view->errors = $this->_errorMessenger->getMessages();
            $this->_errorMessenger->clearMessages();
        } else {
            if ($form->isValid($_POST)) {
                //#region UploadFile
                $fileInfo = $form->deal_avatar->getFileInfo();

                $ext = $this->_findexts($fileInfo['deal_avatar']['name']);
                $filename = 'DEAL_IMAGE_' . md5('HopMua' . date('Y.m.d+H:i:s:u') . 'HopMua') . '_490x327' . '.' . $ext;

                $form->deal_avatar->addFilter('Rename', array(
                    'target' => UPLOAD_DESTINATION . '/images/deals/' . $filename,
                    'overwrite' => true));
                //#endregion

                $values = $form->getValues();

                $model = $this->loadModel('admin_cms', 'Deal');
                $newdeal = $model->createrow();

                $newdeal->deal_title = $values['deal_title'];
                $newdeal->price = (int) $values['product_price'];
                $newdeal->value = (int) $values['value'];
                $newdeal->product_price = (int) $values['product_price'];

                $newdeal->started = $values['started'];
                $newdeal->deadline = $values['deadline'];

                $newdeal->supplier_name = $values['supplier_name'];
                $newdeal->supplier_url = $values['supplier_url'];
                $newdeal->supplier_contact = $values['supplier_contact'];

                $newdeal->deal_quantity = (int) $values['deal_quantity'];

                //update 5 fields                
                $newdeal->number_A = $values['number_A'];
                $newdeal->number_B = $values['number_B'];
                $newdeal->current_barcode = $values['number_A'];
                
                $newdeal->deal_avatar = $filename;

                $newdeal->deal_intro = $values['deal_intro'];
                $newdeal->deal_fulltext = $values['deal_fulltext'];
                $newdeal->deal_notes = $values['deal_notes'];

                $newdeal->status = (int) $values['status'];
                $newdeal->save();

                $redirect_url = $this->getUrl(array("module" => "admin_cms", "controller" => "deal", "action" => "index"));
                $this->_redirect($redirect_url);
            }
        }
    }

    public function editAction() {
        try{
        	$this->view->rightAdminModules('right');

            $model = $this->loadModel('admin_cms', 'Deal');
            $dealid = $this->_request->getParam('id', $this->_request->getParam('deal_id', 1));

            $deal = $model->getDealById($dealid);

            $form = $this->getForm($deal->deal_avatar);
            $form->setAction($this->view->baseUrl('index.php/admin_cms/deal/edit'))->setMethod('post');

            $form->deal_id->setValue($deal->deal_id);
            $form->deal_title->setValue($deal->deal_title);
            $form->category_id->setValue($deal->category_id);
            $form->value->setValue($deal->value);
            $form->product_price->setValue($deal->product_price);

            $form->started->setValue($deal->started);
            $form->deadline->setValue($deal->deadline);

            $form->supplier_name->setValue($deal->supplier_name);
            $form->supplier_url->setValue($deal->supplier_url);
            $form->supplier_contact->setValue($deal->supplier_contact);

            $form->deal_quantity->setValue($deal->deal_quantity);
            
            //load 5 updated fields                
			$form->mail_title->setValue($deal->mail_title);
			$form->mail_content->setValue($deal->mail_content);
			$form->mail_content_succeed->setValue($deal->mail_content_succeed);
			$form->number_A->setValue($deal->number_A);
			$form->number_B->setValue($deal->number_B);

            $form->deal_intro->setValue($deal->deal_intro);
            $form->deal_fulltext->setValue($deal->deal_fulltext);
            $form->deal_notes->setValue($deal->deal_notes);

            $form->status->setValue($deal->status);
            
            if (!$this->_request->isPost()) {
                $this->view->form = $form;

                return $this->render('edit');
            } else {
                if ($form->isValid($_POST)) {

                    #region UploadFile
                    $fileInfo = $form->deal_avatar->getFileInfo();

                    $ext = $this->_findexts($fileInfo['deal_avatar']['name']);
                    $filename = 'DEAL_IMAGE_' . md5('HopMua' . date('Y.m.d+H:i:s:u') . 'HopMua') . '_490x327' . '.' . $ext;

                    $form->deal_avatar->addFilter('Rename', array(
                        'target' => UPLOAD_DESTINATION . '/images/deals/' . $filename,
                        'overwrite' => true));

                    if (!is_null($fileInfo['deal_avatar']['size'])) {
                        $deal->deal_avatar = $filename;
                    }
                    //#endregion

                    $values = $form->getValues();

                    $deal->deal_title = $values['deal_title'];
                    $deal->category_id = $values['category_id'];

                    $deal->price = (int) $values['product_price'];
                    $deal->value = (int) $values['value'];
                    $deal->product_price = (int) $values['product_price'];

                    $deal->started = $values['started'];
                    $deal->deadline = $values['deadline'];

                    $deal->supplier_name = $values['supplier_name'];
                    $deal->supplier_url = $values['supplier_url'];
                    $deal->supplier_contact = $values['supplier_contact'];

                    $deal->deal_quantity = (int) $values['deal_quantity'];
					
                    //update 5 fields                
	                $deal->number_A = $values['number_A'];
	                $deal->number_B = $values['number_B'];
	                
                    $deal->deal_intro = $values['deal_intro'];
                    $deal->deal_fulltext = $values['deal_fulltext'];
                    $deal->deal_notes = $values['deal_notes'];

                    $deal->status = (int) $values['status'];
                    $deal->save();

                    $redirect_url = $this->getUrl(array("module" => "admin_cms", "controller" => "deal", "action" => "index"));
                    $this->_redirect($redirect_url);
                } else {
                    $this->view->form = $form;

                    return $this->render('edit');
                }
            }
        }
        catch(Exception $ex){
            echo $ex->getMessage();
            die;
        }
    }

    public function deleteAction() {
        $model = $this->loadModel('admin_cms', 'Deal');
        $dealid = $this->_request->getParam('id');
        $deal = $model->getDealById($dealid);
        $deal->delete();

        $redirect_url = $this->getUrl(array("module" => "admin_cms", "controller" => "deal", "action" => "index"));
        $this->_redirect($redirect_url);
    }

}
